package com.lp.filter.factory;

import com.lp.common.RedisPrefix;
import com.lp.exception.IllegalTokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;


@Slf4j
@Component // 表示在工厂中创建对象
public class TokenGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenGatewayFilterFactory.Config> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public TokenGatewayFilterFactory() {
        super(Config.class);
    }

    /**
     * 核心方法: 处理过滤
     * @param config
     * @return
     */
    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("config isRequire: {}", config.isRequire());
                log.info("config name: {}", config.getName());
                //1.拿到 Config 中自定义的参数 isRequire，判断是否要进行过滤
                if(config.isRequire()) {
                    //2.获取 token 信息
                    //由于 header 中 key 可以重复(包括 parma 也是如此)，因此获取到的是一个 List
                    List<String> tokens = exchange.getRequest().getHeaders().get(RedisPrefix.TOKEN_KEY);
                    if(tokens == null) {
                        throw new IllegalTokenException("没有 token 令牌！");
                    }
                    String tokenValue = tokens.get(0);
                    log.info("token: {}", tokenValue);
                    //3.比较 redis 上的 token 数据是否一致(redis 上存储的数据格式为: token前缀 + value)
                    if(!redisTemplate.hasKey(RedisPrefix.TOKEN_KEY + tokenValue)) {
                        throw new IllegalTokenException("token 令牌不合法！");
                    }
                }
                return chain.filter(exchange);
            }
        };
    }

    /**
     * 指定参数值填写的顺序
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("require", "name");
    }

    /**
     * 提供 filter 配置中的参数值
     */
    public static class Config {
        private boolean require;
        private String name;

        public boolean isRequire() {
            return require;
        }

        public void setRequire(boolean require) {
            this.require = require;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
